<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form ref="themeForm" :model="themeForm" label-width="80px">
        <el-col :span="8">
          <el-form-item label="皮肤名称">
            <el-input v-model="themeForm.strThemeName" placeholder="请输入皮肤名称" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="机构名称">
            <el-cascader
              v-model="themeForm.iOrgsysnum"
              :show-all-levels="false"
              :options="options"
              :props="{ checkStrictly: true, value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" @click="fetchList">查询</el-button>
            <!-- <el-button type="primary" @click="resetFiles('themeForm')">重置</el-button> -->
            <el-button type="primary" @click="addDialogTheme">添加</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </div>
    <el-table v-loading="tbloading" :data="tableData" style="width: 100%" border>
      <el-table-column type="index" label="序号" width="55" />

      <el-table-column prop="strThemeName" label="皮肤名称" />
      <el-table-column prop="strUrl" label="皮肤链接" align="center">
        <template slot-scope="{row}">
          <a :href="row.strUrl" target="_blank" style="text-decoration: underline;color:blue">查看</a>
        </template>
      </el-table-column>
      <el-table-column prop="strImg" label="皮肤缩略图" align="center">
        <template slot-scope="{row}">
          <el-image
            style="width: 100px; height: 100px"
            :src="row.strImg"
            :preview-src-list="[row.strImg]"
          />
        </template>
      </el-table-column>

      <el-table-column prop="strOperatorname" label="操作者" />
      <el-table-column prop="strOrgName" label="机构名称" />
      <el-table-column prop="strCreatetime" label="创建时间" />
      <el-table-column label="操作" width="220">
        <template slot-scope="{row}">
          <template v-if="row.iOrgsysnum === iOrgsysnum || iOrgsysnum === -1">
            <el-button size="mini" type="primary" @click="modifyRow(row)">修改</el-button>
            <el-button size="mini" type="danger" @click="deleteRow(row)">删除</el-button>
          </template>
          <span v-else>/</span>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="themeForm.pageNum"
      :limit.sync="limit"
      :layout="layout"
      @pagination="fetchList"
    />

    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="width"
      :close-on-click-modal="false"
    >
      <el-form ref="dialogForm" :model="dialogForm" :rules="dialogFormRules" label-width="100px">
        <el-form-item label="皮肤名称" prop="strThemeName">
          <el-col :span="12">
            <el-input v-model="dialogForm.strThemeName" placeholder="请输入皮肤名称" />
          </el-col>
        </el-form-item>
        <el-form-item label="皮肤缩略图" prop="strImg">
          <el-upload
            :action="baseImgRUL"
            name="uploadFile"
            class="avatar-uploader"
            :show-file-list="false"
            :on-success="(response, file)=>handleSuccess(response, file, 'dialogForm', 'strImg')"
            :before-upload="beforeUpload"
          >
            <img v-if="dialogForm.strImg" :src="dialogForm.strImg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>
        </el-form-item>
        <el-form-item label="皮肤文件" prop="strUrl">
          <el-upload
            :action="baseImgRUL"
            name="uploadFile"
            :file-list="fileList"
            :on-success="(response, file)=>handleSkinSuccess(response, file, 'dialogForm', 'strUrl')"
            :before-upload="beforeSkinUpload"
            :on-exceed="handleExceed"
            :limit="1"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="操作者">
          <el-col :span="12">
            <el-input v-model="dialogForm.strOperator" disabled />
          </el-col>
        </el-form-item>
        <el-form-item label="设备类型" prop="iDevicetype">
          <el-select v-model="dialogForm.iDevicetype" placeholder="请选择设备类型">
            <el-option
              v-for="item in optionsType"
              :key="item.id"
              :label="item.strValue"
              :value="item.strCode"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属机构" prop="iOrgsysnum">
          <el-cascader
            v-model="dialogForm.iOrgsysnum"
            :show-all-levels="false"
            :options="options"
            :props="{ checkStrictly: true, value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
            @change="handleClick"
          />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="cancleDialog('dialogForm')">取 消</el-button>
        <el-button
          v-if="dialogTitle === dialogOptions.add"
          v-preventReClick
          type="primary"
          @click="confirmSubmit('dialogForm')"
        >确 定</el-button>
        <el-button v-else v-preventReClick type="primary" @click="modifiedSubmit('dialogForm')">修 改</el-button>
      </div>
    </el-dialog>
    <!-- <DialogCom :form-data="dialogForm" :dialog-title="dialogTitle" :dialog-visible="dialogVisible" :options-type="optionsType" :options="options" /> -->
  </div>
</template>

<script>
import { fetchThemeData, deleteRowTheme, confirmAddTheme, updateRowTheme } from '@/api/themeapi/index'
import Pagination from '@/components/Pagination/index'
import { getOrglist, getParentNumArr, getSysType } from '@/api/common'
// import DialogCom from './components/dialogCom'
import uploadImg from '@/mixins/uploadImg'
import uploadFiles from '@/mixins/uploadFiles'
import { mapGetters } from 'vuex'
const validateValue = (rule, value, callback) => {
  const reg = /^[\u4E00-\u9FA5A-Za-z0-9]{1,15}$/ // 1-15个汉字、字母、数字
  if (value === '') {
    callback(new Error('请输入皮肤名称'))
  } else if (!reg.test(value)) {
    callback(new Error('只能输入中文、英文和数字'))
  } else {
    callback()
  }
}
export default {
  name: 'Theme',
  components: { Pagination },
  mixins: [uploadImg, uploadFiles],
  data() {
    return {
      tableData: [],
      total: 0,
      limit: 5,
      tbloading: false,
      options: [],
      optionsType: [],
      layout: 'total, prev, pager, next, jumper',
      dialogTitle: '',
      dialogVisible: false,
      themeForm: {
        strThemeName: '',
        iOrgsysnum: '',
        pageNum: 1
      },
      fileList: [],
      dialogFormRules: {
        strThemeName: [
          { required: true, validator: validateValue, trigger: 'blur' }
        ],
        strUrl: [
          { required: true, message: '请上传皮肤文件', trigger: 'blur' }
        ],
        strImg: [
          { required: true, message: '请上传皮肤缩略图', trigger: 'change' }
        ],
        iOrgsysnum: [
          { required: true, message: '请选择机构类型', trigger: 'change' }
        ],
        iDevicetype: [
          { required: true, message: '请选择设备类型', trigger: 'change' }
        ]
      },
      dialogOptions: {
        add: '添加皮肤',
        editTheme: '修改皮肤'
      },
      dialogForm: {
        strThemeName: '',
        strUrl: '',
        strImg: '',
        strOperator: this.name,
        iDevicetype: '',
        iOrgsysnum: ''
      }
    }
  },
  computed: {
    ...mapGetters(['iOrgsysnum', 'name', 'userID'])
  },
  created() {
    Promise.all([this.fetchOrg(), this.fetchList()])
    this.dialogForm.strOperator = this.name || 'Super Admin'
  },
  methods: {
    fetchList() {
      if (this.themeForm.iOrgsysnum instanceof Array) {
        this.themeForm.iOrgsysnum = this.themeForm.iOrgsysnum.splice(-1)[0]
      } else {
        this.themeForm.iOrgsysnum = this.themeForm.iOrgsysnum
      }
      if (this.themeForm.strThemeName === '') {
        delete this.themeForm.strThemeName
      }
      if (this.themeForm.iOrgsysnum === '') {
        delete this.themeForm.iOrgsysnum
      }
      this.tbloading = true
      fetchThemeData(this.themeForm).then(res => {
        this.tableData = res && res.data
        this.total = !res ? 0 : res.total
        this.tbloading = false
      }).catch(e => {
        this.tbloading = false
      })
    },
    fetchOrg() {
      getOrglist().then(res => {
        this.options = res.data
      })
      getSysType({ typeInfo: [7] }).then(res => {
        this.optionsType = res.data[7]
      })
    },
    resetFiles(formName) {
      this.$refs[formName].resetFields()
    },
    addDialogTheme() {
      this.dialogTitle = this.dialogOptions.add
      this.dialogForm = {
        strThemeName: '',
        strUrl: '',
        strImg: '',
        strOperator: this.name,
        iDevicetype: '',
        iOrgsysnum: ''
      }
      this.dialogVisible = true
      this.$nextTick(_ => {
        this.$refs['dialogForm'].clearValidate()
      })
    },
    deleteRow(row) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(res => {
        console.log(res)
        deleteRowTheme({ iThemeNum: row.iThemeNum }).then(res => {
          this.$message({ type: 'success', message: '删除成功' })
          this.fetchList()
        })
      }).catch(err => {
        this.$message({ message: '取消删除' })
        console.log(err)
      })
    },
    modifyRow(row) {
      this.dialogForm = row
      this.dialogTitle = this.dialogOptions.editTheme
      // this.dialogForm.iDevicetype = row.iDevicetype.toString()
      this.dialogForm = {
        strThemeName: row.strThemeName,
        strUrl: row.strUrl,
        strImg: row.strImg,
        strOperator: this.name,
        iDevicetype: row.iDevicestype + '',
        iThemeNum: row.iThemeNum,
        iOrgsysnum: []
      }
      this.fileList.push({
        name: row.strThemeName,
        url: row.strUrl
      })
      getParentNumArr({ iOrgsysnum: row.iOrgsysnum }).then(res => {
        this.dialogForm.iOrgsysnum = res.data.split(',')
        this.dialogVisible = true
      })
    },
    cancleDialog(formName) {
      this.$refs[formName].resetFields()
      this.fileList = []
      this.dialogVisible = false
    },
    confirmSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const query = this.dialogForm
          if (query.iOrgsysnum instanceof Array) {
            query.iOrgsysnum = query.iOrgsysnum.splice(-1)[0]
          }
          query.strOperator = this.userID
          confirmAddTheme(query).then(res => {
            this.$message({
              type: 'success',
              message: '添加成功'
            })
            this.dialogVisible = false
            this.fetchList()
            this.fileList = []
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      // this.dialogVisible = false
      // this.$refs[formName].resetFiles()
    },
    modifiedSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const query = this.dialogForm
          if (query.iOrgsysnum instanceof Array) {
            query.iOrgsysnum = query.iOrgsysnum.splice(-1)[0]
          } else {
            query.iOrgsysnum = this.dialogForm.iOrgsysnum
          }
          query.strOperator = this.userID
          updateRowTheme(query).then(res => {
            this.$message({
              type: 'success',
              message: '修改成功'
            })
            this.dialogVisible = false
            this.fetchList()
            this.fileList = []
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
      // this.dialogVisible = false
      // this.$refs[formName].resetFiles()
    },
    handleClick(val) {
      console.log(val)
    }

  }
}
</script>
<style lang="scss" scope>
/deep/ .el-form-item .el-form-item__content {
  margin-left: 0;
}
</style>
